package com.ruoyi.web.petmall.uitl;

import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.BatchStatus;
import com.qiniu.util.Auth;
import com.qiniu.storage.Configuration;
import org.springframework.util.DigestUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;


public class SevenCowCloudUtil {

    //通行证
    private static final String QiniuCloud_accessKey = "Dg6TOi9EATgzjuy2y1eGlfP_WC5gMsG9rYUURYIL";

    //安全密钥
    private static final String QiniuCloud_secretKey = "Tk0t_sgF37GzVDr-ZEn27EnZKdX3ETrEMcztEVHf";

    //存储空间名称
    private static final String QiniuCloud_bucket = "pet--mall--picture";
    private static final String QiniuCloud_domainName = "http://sgn4h6k2h.hb-bkt.clouddn.com/";
    private static final String imageCustomSuffix = ".jpg";//定义图片保存后的后缀

    /**
     * 上传图片到七牛云
     * @param file 图片
     * @return 返回图片存储后的新图片名
     * @throws Exception
     */
    public static Object QiniuCloudUploadImage(MultipartFile file) throws IOException {
        if(file.isEmpty()) {
            return "文件为空";
        }else if(file.getSize() > 1024*1024*10){
            return "文件大于10M";
        }
        //获取图片后缀
        String originalFilename = file.getOriginalFilename();
        assert originalFilename != null;
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        //允许上传的图片格式集合
        String[] suffixes = new String[]{".bmp", ".jpeg", ".jpg", ".png"};
        boolean bool = false;
        //判断格式是否在suffixes中
        for(String string : suffixes){
            if (string.equals(suffix)){
                bool = true;
                break;
            }
        }
        if(!bool){
            return "图片格式错误";
        }
        //构造一个带指定 Region 对象的配置类
        Configuration cfg = new Configuration(Region.autoRegion());
        cfg.resumableUploadAPIVersion = Configuration.ResumableUploadAPIVersion.V2;//指定分片上传版本
        UploadManager uploadManager = new UploadManager(cfg);
        //生成上传凭证，然后准备上传
        byte[] bytes = file.getBytes();
        String imageName = DigestUtils.md5DigestAsHex(bytes);//将图片md5的值作为图片名，避免重复图片浪费空间
        //默认不指定key的情况下，以文件内容的hash值作为文件名
        //QiniuCloud_domainName +
        String key = imageName + imageCustomSuffix;//图片保存到七牛云后的文件名

        try {
            byte[] uploadBytes = file.getBytes();
            ByteArrayInputStream byteInputStream=new ByteArrayInputStream(uploadBytes);
            Auth auth = Auth.create(QiniuCloud_accessKey, QiniuCloud_secretKey);
            String upToken = auth.uploadToken(QiniuCloud_bucket);

            try {
                uploadManager.put(byteInputStream,key,upToken,null, null);
            } catch (QiniuException ex) {
                Response r = ex.response;
                System.err.println("七牛云ERROR:" + r.toString());
                try {
                    System.err.println("七牛云ERROR:" + r.bodyString());
                } catch (QiniuException ex2) {
                    //ignore
                }
            }
        } catch (UnsupportedEncodingException ex) {
            //ignore
        }
        return QiniuCloud_domainName + key;
    }


    /**
     * 从七牛云删除图片
     * @param fileNameList 图片名集合
     * @return 返回每张图片的删除结果
     */
    public static Object QiniuCloudDeleteImage(String[] fileNameList){
        //用Json格式传数组时直接传["xxx", "xxx", "xxx", "xxx"]
        //构造一个带指定 Region 对象的配置类
        Configuration cfg = new Configuration(Region.region0());
        //生成凭证
        Auth auth = Auth.create(QiniuCloud_accessKey, QiniuCloud_secretKey);
        BucketManager bucketManager = new BucketManager(auth, cfg);
        //创建一个用来接收删除结果的集合
        List<String> list = new ArrayList<>();
        try {
            //单次批量请求的文件数量不得超过1000
            BucketManager.BatchOperations batchOperations = new BucketManager.BatchOperations();
            batchOperations.addDeleteOp(QiniuCloud_bucket, fileNameList);
            Response response = bucketManager.batch(batchOperations);
            BatchStatus[] batchStatusList = response.jsonToObject(BatchStatus[].class);
            for (int i = 0; i < fileNameList.length; i++) {
                BatchStatus status = batchStatusList[i];
                if (status.code == 200) {//成功返回文件名+true并添加进集合
                    list.add("{fileName:"+fileNameList[i]+",deleteResult:true}");
                }else {//失败返回文件名+false并添加进集合
                    list.add("{fileName:"+fileNameList[i]+",deleteResult:false}");
                }
            }
        } catch (QiniuException ex) {
            System.err.println("七牛云ERROR:" + ex.response.toString());
        }
        return list;
    }

    /**
     * 从七牛云中获取图片
     * @param fileName
     */
    public static String getFilePath(String fileName) {

        //设置图片存储的位置
        String publicUrl = QiniuCloud_domainName + "/" + fileName;

        //认证并进入七牛云存储进行操作
        Auth auth = Auth.create(QiniuCloud_accessKey,QiniuCloud_secretKey);
        long expireInSeconds = 36000; //1小时，可以自定义链接过期时间
        //通过设置的位置以及设置的过期时间，进行查询以及获取操作
        String finalUrl = auth.privateDownloadUrl(publicUrl, expireInSeconds);
        System.out.println(finalUrl);
        return finalUrl;
    }
}
